/*-
 * AtCommand.java
 *
 * Copyright (c) 2007, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.at;

import static com.googlecode.attention.ComLogStatements.*;

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.attention.CMEError;


/**
 * AT Command.
 *
 * @author Stein Gunnar Bakkeby
 */
public abstract class AtCommand<AT extends AtCommand<AT>> {
  
  protected Command type;
  protected String command;
  protected boolean success = false;
  protected LinkedList<AtListener<AT>> listeners;
  private Class<?> sender;
  private CMEError error;
  
  public AtCommand(AtListener<AT> listener) {
    addListener(listener);
  }
    
  /**
   * Sets the AT command.
   * 
   * @param command The AT command to send
   * @param type The command type
   */
  protected void setCommand(final String command, final Command type) {
    this.command = command;
    this.type = type;
  }
  
  void setSender(final Class<?> sender) {
    this.sender = sender;
  }

  /**
   * This will set the listener for the response from the mobile.
   * 
   * @param listener The AT listener
   */
  public void addListener(final AtListener<AT> listener) {
    if (listeners == null) {
      listeners = new LinkedList<AtListener<AT>>();
    }
    if (listener != null) listeners.add(listener);
  }
  
  /**
   * This will parse the response from the AT command.
   * 
   * @param response The AT response 
   */
  public void parse(final String response) {
    //COM_DEBUG.log("Parsing AT command: " + this.toString());
    parseSuccess(response);
    
    switch(type) {
    case TEST:
      parseTest(response);
      break;
    
    case READ:
      parseRead(response);
      break;
      
    case WRITE:
      parseWrite(response);
      break;
      
    case EXECUTE:
      parseExecute(response);
      break;
      
    default:
      /* Unknown */
      throwError(response);
    }
    notifyListeners();
  }
  
  /**
   * This will notify all listeners.
   */
  public void notifyListeners() {
    if (listeners == null || listeners.size() == 0) {
      if (sender != null) {
        COM_008.log(getThis().getClass().getName(),sender.getName());
      } else {
        COM_008.log(getThis().getClass().getName(),"Mobile");
      }
    } else {
      AT object = getThis();
      if (success) {
        for (AtListener<AT> listener : listeners) {
          if (listener != null) listener.atSuccess(object);
        }
      } else {
        for (AtListener<AT> listener : listeners) {
          if (listener != null) listener.atFailure(object);
        }
      }
    }
  }
  
  protected abstract AT getThis();
  
  protected void parseSuccess(final String response) {
    success = removeCRLF(response).trim().endsWith("OK");
    if (!success) {
      final Pattern pattern = Pattern.compile("\\+CM[E|S] ERROR: ([0-9]+)");
      final Matcher matcher = pattern.matcher(response);
      if (matcher.find()) {
        error = CMEError.parse(matcher.group(1));
      }
    }
  }
  
  protected void parseTest(final String response) {
//    throwError(response);
  }
  
  protected void parseRead(final String response) {
//    throwError(response);
  }
  
  protected void parseWrite(final String response) {
//    throwError(response);
  }
  
  protected void parseExecute(final String response) {
//    throwError(response);
  }
  
  protected String removeCRLF(final String input) {
    return input.replaceAll("\n", "").replaceAll("\r", "").toUpperCase();
  }
  
  private void throwError(final String response) {
    throw new RuntimeException(
        "[Unknown AT: " + command
      + "][Type: " + type
      + "][Response: " + response + "]");
  }
  
  /**
   * This will return the AT command.
   * 
   * @return The AT command.
   */
  public String getCommand() {
    return command;
  }
  
  public String toString() {
    return "[" + command + "]";
  }
  
  /**
   * This will return the error code, or null if not present. Errors
   * in relation to AT commands often only state "ERROR", in this case this
   * method will return {@link CMEError#ERROR}.
   * 
   * @return CME error, or null if not present
   * @see CMEError
   */
  public CMEError getErrorCode() {
    return error;
  }
}
